import javax.swing.*;
import java.sql.*;

public class MysqlTestDemo
{
    private static final String URL = "jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC";
    private static final String user = "root";
    private static final String password = "wl249020...";
    public static void main(String[] args) throws Exception
    {
        Connection connection = null;
        try{
            connection = DriverManager.getConnection(URL,user,password);
            DatabaseMetaData metaData = connection.getMetaData();
            String driverVersion = metaData.getDriverVersion();
            System.out.println("JDBC driver version is " + driverVersion);
            Person person = new Person("person.name",34);
            insertPerson(connection,person);
            printSelectResult(connection);
        }catch (ClassNotFoundException | SQLException e)
        {
            e.printStackTrace();
        }
    }

    public static void insertPerson(Connection conn, Person person) throws Exception
    {
        // 预编译sql
        String sql = "insert into person (name,age) values (?,?)";
        PreparedStatement pst = conn.prepareStatement(sql);
        pst.setString(1,person.getName());
        pst.setInt(2,person.getAge());
        int i = pst.executeUpdate();
        System.out.println(i);


    }

    public static void printSelectResult(Connection connection)
    {
        String sql = "select * from person";
        try
        {
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(sql);
            while (resultSet.next())
            {
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                System.out.println(name + "  " + age + "\t");
            }
        } catch (SQLException e)
        {
            throw new RuntimeException(e);
        }


    }

}



class Person
{
    private String name;
    private int age;

    public Person(String name,int age)
    {
        this.setAge(age);
        this.setName(name);
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public int getAge()
    {
        return age;
    }

    public void setAge(int age)
    {
        this.age = age;
    }
}